# -*- coding: utf-8 -*-

import requests
from PyQt5.QtCore import QSettings,Qt
from PyQt5.QtWidgets import QWidget, QMessageBox, QMainWindow, QLineEdit
import sys, json

import constant
from ui import login
from utils import api


class LoginWindow(QMainWindow, login.Ui_Login):

    token = None

    def __init__(self):
        super().__init__()
        self.setupUi(self)
        #self.input_phone.setText('15875551880')
        #self.input_password.setText('000000')
        self.input_password.setEchoMode(QLineEdit.Password)
        self.btn_login.clicked.connect(self.btnLoginClick)
        self.input_autologin.clicked.connect(self.inputAutologinClick)
        self.input_autologin.setTristate(False)

        # 初始化QSettings对象，指定应用程序名称和文件路径
        self.settings = QSettings(constant.APP_NAME, 'config.ini')
        auto_login = self.settings.value('auto_login', defaultValue=0)
        if auto_login == 1:
            self.loadLoginData()

    def closeEvent(self, event):
        print("token")
        print(self.token)
        if self.token is None:
            result = QMessageBox.question(self, "恒通房管", "确定要退出吗?",
                                          QMessageBox.Yes | QMessageBox.No)
            if result == QMessageBox.Yes:
                event.accept()
            else:
                event.ignore()

    def btnLoginClick(self):
        self.inputAutologinClick()
        self.token = api.login(self)

    def inputAutologinClick(self):
        if self.input_autologin.isChecked():
            if self.input_phone.text() == "":
                QMessageBox.about(self, '提示', "请输入手机号码！")
                self.input_autologin.setCheckState(False)
            elif self.input_password.text() == "":
                QMessageBox.about(self, '提示', "请输入登录密码！")
                self.input_autologin.setCheckState(False)
            else:
                # 保存数据
                self.settings.setValue('username', self.input_phone.text())
                self.settings.setValue('password', self.input_password.text())
                self.settings.setValue('auto_login', 1)
        else:
            self.settings.setValue('auto_login', 0)
            self.settings.remove('username')
            self.settings.remove('password')

    def loadLoginData(self):
        self.input_autologin.setCheckState(Qt.Checked)
        # 读取数据
        self.input_phone.setText(self.settings.value('username'))
        self.input_password.setText(self.settings.value('password'))

